<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Carbon;

/**
 * App\Models\UserCard
 *
 * @property int $id
 * @property int $order_id 订单ID
 * @property int $user_id 用户ID
 * @property int $car_id 车辆ID
 * @property int $card_id 会员卡ID
 * @property string $title 标题
 * @property float $price 购买价格
 * @property int $number 洗车次数
 * @property int $old_number 原洗车次数
 * @property int $discount 折扣
 * @property int $range 使用限制:0=全场通用,1=指定服务
 * @property int $shop_id 门店ID
 * @property string|null $areas 所属地区ID组,默认null表示全国地区显示
 * @property string $start_time 开启日期
 * @property string $end_time 结束日期
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property-read \App\Models\User|null $user
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard query()
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereAreas($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereCarId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereCardId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereEndTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereNumber($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereOldNumber($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard wherePrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereRange($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereShopId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereStartTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCard whereUserId($value)
 * @mixin \Eloquent
 */
class UserCard extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'user_cards';

    protected $fillable = [
        "user_id","title","range","car_id","car_num","price","car","number","order_id","shop_id",
        "service_id","price","start_time","end_time","old_number","card_id","discount","content"
    ];

    protected $casts = ['price'=>'float',"car"=>"json"];

    protected $appends = [

    ];

    protected $hidden = [
        'number','old_number'
    ];

    protected static function booted()
    {
        self::created(function (UserCard $userCard){
            OrderCommission::addCardCommission($userCard);
        });
    }

    /**
     * 添加洗车卡
     * @param $order_id
     * @param $user_id
     * @param $extend
     * @return UserCard|Model
     */
    public static function addCard($order_id,$user_id,$extend)
    {
        $card = $extend['card'];
        $car = $extend['car'];
        unset($car['created_at']);
        unset($car['updated_at']);
        unset($car['is_default']);
        $params = [
            'user_id'=>$user_id,"card_id"=>$card['id'],
            'title'=>$card['title'],'range'=>$card['range'],
            'price'=>$card['price'],'shop_id'=>$card['shop_id'],
            'car_id'=>$car['id'],'car_num'=>$car['plate_number'],"car"=>$car,
            "order_id"=>$order_id,"number"=>$card['number'],"old_number"=>$card['number'],
            'discount'=>$card['discount'],"content"=>$card['content']
        ];
        $days = $card['days'];
        $start_time = now()->format("Y-m-d");
        $end_time = now()->addDays($days)->format("Y-m-d");
        $params['start_time'] = $start_time;
        $params['end_time'] = $end_time;
        $res = self::create($params);
        if ($res){
            $user_card_id = $res->id;
            $data = [
                'user_id'=>$user_id,"card_id"=>$card['id'],"user_card_id"=>$user_card_id,'range'=>$card['range'],
                'shop_id'=>$card['shop_id'],'car_id'=>$car['id'],'car_num'=>$car['plate_number'],
                "number"=>$card['number'],"old_number"=>$card['number'],'discount'=>$card['discount'],
                'start_time'=>$start_time,'end_time'=>$end_time
            ];
            if ($card['range']){
                $services = $card['services'];
                if ($services){
                    foreach ($services as $item){
                        $number = $item['number'];
                        $data['number'] = $number;
                        $data['old_number'] = $number;
                        $data['service_id'] = $item['s_id'];
                        $data['service_name'] = $item['title'];
                        UcService::create($data);
                    }
                }
            }else{
                $data['service_id'] = 0;
                $data['service_name'] = "";
                UcService::create($data);
            }
        }
        return $res;
    }

    public function user(): HasOne
    {
        return $this->hasOne(User::class,"id","user_id");
    }

    public function order(): HasOne
    {
        return $this->hasOne(PaymentOrder::class,"id","order_id");
    }

    /**
     * 获取洗车卡列表
     * @param $user_id
     * @return array
     */
    public static function getList($user_id): array
    {
        $pageSize = request()->input("pageSize",10);
        $type = request()->input("type",0);
        $where = ['user_id'=>$user_id];
        $model = self::query()->where($where);
        if ($type){
            $query = $model->whereDate("start_time",">",now())
                ->whereDate("end_time","<",now());
        }else{
            $query = $model->whereDate("start_time","<=",now())
                ->whereDate("end_time",">=",now());
        }
        $list = $query->orderByDesc("id")->paginate($pageSize);
        $data['items'] = $list->items();
        $data['lastPage'] = $list->lastPage();
        $data['total'] = $list->total();
        return $data;
    }
    public static function getDetail($id, $user_id): array
    {
        $card = self::query()->with(['services'])->where("id",$id)->first();
        $data['item'] = $card;
        return $data;
    }
    /**
     * @param $user_id
     * @return array
     */
    public static function allows($user_id): array
    {
        $service_id = request()->input("service_id","");
        $car_id = request()->input("car_id","");
        $service = Service::find($service_id);
        if (!$service){
            modelError("找不到此服务!");
        }
        $shop_id = $service->shop_id;
        $car = UserCar::query()->where("id",$car_id)->first();
        if (!$car){
            modelError("找不到此车牌号信息!");
        }
        $plate_number = $car->plate_number;

        $map1 = ["range"=>0,'user_id'=>$user_id,"car_id"=>$car_id,"car_num"=>$plate_number,"service_id"=>0,"shop_id"=>$shop_id];
        $map2 = $map1;
        $map2["range"] = 1;
        $map2["service_id"] = $service_id;
        $list = self::query()
            ->with(['services'])
            ->where("shop_id",$shop_id)
            ->where("user_id",$user_id)
            ->where("car_id",$car_id)
            ->where("car_num",$plate_number)
            ->where("start_time","<=",now())
            ->where("end_time",">=",now())
            ->whereIn("id",function ($query) use ($map1,$map2){
                $query->from("uc_service")->select(["user_card_id"])->where($map1)->orWhere($map2);
            })
            ->get();
        return $list->toArray();
    }

    public function services(){
        return $this->hasMany(UcService::class,"user_card_id","id");
    }

}
